from collections import OrderedDict

from goods.models import GoodsChannel


def get_categories():
    """
    获取商品分类字典
    :return: 商品分类字典
    """
    #建立一个有序字典，存储所有数据
    categories = OrderedDict()

    # 找出所有的频道,并排序
    channels = GoodsChannel.objects.order_by('group_id','sequence')
    for channel in channels:
        group_id = channel.group_id
        # 没有频道组，就创建相应的频道组
        if not group_id in categories:
            categories[group_id] = {'channels':[],'sub_cats':[]}
        # 一级类别
        cat1 = channel.category
        # 一级类别归类,根据频道组
        categories[group_id]['channels'].append({
            'id':cat1.id,
            'name':cat1.name,
            'url':channel.url
        })
        # 二级类别归类
        for cat2 in cat1.subs.all():
            cat2.sub_cats = []
            # 三级类别归类
            for cat3 in cat2.subs.all():
                cat2.sub_cats.append(cat3)
            categories[group_id]['sub_cats'].append(cat2)
    return categories